package com.zf.shuashua.video;

import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.apsara.alivclittlevideo.net.NetWatchdog;
import com.aliyun.apsara.alivclittlevideo.net.data.LittleMineVideoInfo;
import com.aliyun.apsara.alivclittlevideo.sts.OnStsResultListener;
import com.aliyun.apsara.alivclittlevideo.sts.StsInfoManager;
import com.aliyun.apsara.alivclittlevideo.view.video.BaseVideoSourceModel;
import com.aliyun.apsara.alivclittlevideo.view.video.OnStsInfoExpiredListener;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.AlivcVideoListView;
import com.aliyun.svideo.base.sts.StsTokenInfo;
import com.meis.base.mei.utils.NumberUtils;
import com.zf.shuashua.R;
import com.zf.shuashua.base.BaseActivity;
import com.zf.shuashua.bean.HotData1;
import com.zf.shuashua.bean.HotVideoList;
import com.zf.shuashua.bean.LikeVideo;
import com.zf.shuashua.bean.ListVideo;
import com.zf.shuashua.bean.MeLikeVideoList;
import com.zf.shuashua.bean.MoreMeVideoList;
import com.zf.shuashua.bean.VideoInfo;
import com.zf.shuashua.bean.VideoList;
import com.zf.shuashua.event.UpdateCommentNumberEvent;
import com.zf.shuashua.ui.home.HomeCommentFragment;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class VideoPlayActivity extends BaseActivity {

    private AlivcVideoPlayView videoPlayView;
    private ArrayList<LittleMineVideoInfo.VideoListBean> videoList = new ArrayList<>();
    private NetWatchdog netWatchdog;


    @Override
    protected void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        initToolBar(toolbar, true, "");

        initNetWatchDog();
        initVideoPlayView();

        int position = getIntent().getIntExtra("position", 0);
        boolean isPublish = getIntent().getBooleanExtra("is_publish", false);
        VideoList dataList = (VideoList) getIntent().getSerializableExtra("dataList");
//        LikeVideoList likeList = (LikeVideoList) getIntent().getSerializableExtra("likeList");
//        MeVideoList meList = (MeVideoList) getIntent().getSerializableExtra("meList");
        MoreMeVideoList moreMeList = (MoreMeVideoList) getIntent().getSerializableExtra("moreMeList");
        MeLikeVideoList moreLikeList = (MeLikeVideoList) getIntent().getSerializableExtra("moreLikeList");
        VideoList searchVideoList = (VideoList) getIntent().getSerializableExtra("searchList");
        VideoInfo hotdataList = (VideoInfo) getIntent().getSerializableExtra("hotdataList");

        HotVideoList hotdataListitem = (HotVideoList) getIntent().getSerializableExtra("hotdataListitem");

        if (dataList != null) {
            for (VideoInfo dataBean : dataList.getDataList()) {
                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
                videoListBean.setVideoId(dataBean.getMedia_id());
                videoListBean.setVideoUrl(dataBean.getMedia_url());
                videoListBean.setFirstFrameUrl(dataBean.getAvatar());
                videoListBean.setDescription(dataBean.getDescription());
                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
                userBean.setAvatarUrl(dataBean.getUser().getAvatar());
                userBean.setUserId(dataBean.getUser().getId() + "");
                userBean.setUserName(dataBean.getUser().getName());
                videoListBean.setUser(userBean);
                videoListBean.setType(dataBean.getType());
                videoListBean.setId(dataBean.getId());
                videoListBean.setShareUrl(dataBean.getMedia_url());//创视屏链接
                videoListBean.setTitle(dataBean.getTitle());
                videoListBean.setLocation(dataBean.getLocation());
                videoListBean.setCommentCount(dataBean.getComment_count());
                videoListBean.setPraiseCount(dataBean.getPraise_count());
                videoListBean.setForwardCount(dataBean.getForward_count());
                videoListBean.setFollow_status(dataBean.getFollow_status());
                videoList.add(videoListBean);
            }
            videoPlayView.refreshVideoList(videoList, position);
        }

//        if (likeList != null) {
//            for (Me.MetaBean.VideoLikeBean dataBean : likeList.getDataList()) {
//                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
//                videoListBean.setVideoId(dataBean.getLikable().getMedia_id());
//                videoListBean.setVideoUrl(dataBean.getLikable().getMedia_url());
//                videoListBean.setFirstFrameUrl(dataBean.getLikable().getAvatar());
//                videoListBean.setDescription(dataBean.getLikable().getDescription());
//                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
//                userBean.setAvatarUrl(dataBean.getLikable().getAvatar());
//                userBean.setUserId(dataBean.getUser_id() + "");
//                userBean.setUserName("");
//                videoListBean.setUser(userBean);
//                videoListBean.setId(dataBean.getLikable_id());
//                videoListBean.setShareUrl(dataBean.getLikable().getMedia_url());
//                videoListBean.setTitle(dataBean.getLikable().getTitle());
//                videoListBean.setLocation(dataBean.getLikable().getLocation());
//                videoListBean.setCommentCount(dataBean.getLikable().getComment_count());
//                videoListBean.setPraiseCount(dataBean.getLikable().getPraise_count());
//                videoListBean.setForwardCount(dataBean.getLikable().getForward_count());
//                videoList.add(videoListBean);
//            }
//            videoPlayView.refreshVideoList(videoList, position);
//        }
//
//        if (meList != null) {
//            //我发布的视屏
//            for (Me.MetaBean.VideoListBean.DataBeanX dataBean : meList.getDataList()) {
//                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
//                videoListBean.setVideoId(dataBean.getMedia_id());
//                videoListBean.setVideoUrl(dataBean.getMedia_url());
//                videoListBean.setFirstFrameUrl(dataBean.getAvatar());
//                videoListBean.setDescription(dataBean.getDescription());
//                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
//                userBean.setAvatarUrl(dataBean.getAvatar());
//                userBean.setUserId(dataBean.getUser_id() + "");
//                userBean.setUserName("");
//                videoListBean.setUser(userBean);
//                videoListBean.setId(dataBean.getId());
//                videoListBean.setShareUrl(dataBean.getMedia_url());
//                videoListBean.setTitle(dataBean.getTitle());
//                videoListBean.setLocation(dataBean.getLocation());
//                videoListBean.setCommentCount(dataBean.getComment_count());
//                videoListBean.setPraiseCount(dataBean.getPraise_count());
//                videoListBean.setForwardCount(dataBean.getForward_count());
//                videoListBean.setPublish(isPublish);
//                videoList.add(videoListBean);
//            }
//            videoPlayView.refreshVideoList(videoList, position);
//        }


        if (moreMeList != null) {
            //查看更多里我发布的视屏
            for (ListVideo.DataBean dataBean : moreMeList.getDataList()) {
                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
                videoListBean.setVideoId(dataBean.getMedia_id());
                videoListBean.setVideoUrl(dataBean.getMedia_url());
                videoListBean.setFirstFrameUrl(dataBean.getAvatar());
                videoListBean.setDescription(dataBean.getDescription());
                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
                userBean.setAvatarUrl(dataBean.getUser().getAvatar());
                userBean.setUserId(dataBean.getUser().getId() + "");
                userBean.setUserName(dataBean.getUser().getName());
                videoListBean.setUser(userBean);
                videoListBean.setType(dataBean.getType());
                videoListBean.setId(dataBean.getId());
                videoListBean.setShareUrl(dataBean.getMedia_url());
                videoListBean.setTitle(dataBean.getTitle());
                videoListBean.setLocation(dataBean.getLocation());
                videoListBean.setCommentCount(dataBean.getComment_count());
                videoListBean.setPraiseCount(dataBean.getPraise_count());
                videoListBean.setForwardCount(dataBean.getForward_count());
                videoListBean.setPublish(isPublish);
                videoList.add(videoListBean);
            }
            videoPlayView.refreshVideoList(videoList, position);
        }


        if (moreLikeList != null) {
            //查看更多里我喜欢的视屏
            for (LikeVideo.DataBean dataBean : moreLikeList.getDataList()) {
                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
                videoListBean.setVideoId(dataBean.getLikable().getMedia_id());
                videoListBean.setVideoUrl(dataBean.getLikable().getMedia_url());
                videoListBean.setFirstFrameUrl(dataBean.getLikable().getAvatar());
                videoListBean.setDescription(dataBean.getLikable().getDescription());
                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
                ListVideo.DataBean.UserBean user = dataBean.getVideo().getUser();
                if (user != null) {
                    userBean.setAvatarUrl(user.getAvatar());
                    userBean.setUserId(user.getId() + "");
                    userBean.setUserName(user.getName());
                    videoListBean.setUser(userBean);
                }
                videoListBean.setType(dataBean.getLikable().getType());
                videoListBean.setId(dataBean.getLikable_id());
                videoListBean.setShareUrl(dataBean.getLikable().getMedia_url());
                videoListBean.setTitle(dataBean.getLikable().getTitle());
                videoListBean.setLocation(dataBean.getLikable().getLocation());
                videoListBean.setCommentCount(dataBean.getLikable().getComment_count());
                videoListBean.setPraiseCount(dataBean.getLikable().getPraise_count());
                videoListBean.setForwardCount(dataBean.getLikable().getForward_count());
                videoList.add(videoListBean);
            }
            videoPlayView.refreshVideoList(videoList, position);
        }

        if (searchVideoList != null) {
            for (VideoInfo dataBean : searchVideoList.getDataList()) {
                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
                videoListBean.setVideoId(dataBean.getMedia_id());
                videoListBean.setVideoUrl(dataBean.getMedia_url());
                videoListBean.setFirstFrameUrl(dataBean.getAvatar());
                videoListBean.setDescription(dataBean.getDescription());
                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
//                userBean.setAvatarUrl(dataBean.getLikable().getAvatar());
                userBean.setUserId(dataBean.getUser_id() + "");
                userBean.setUserName("");
                videoListBean.setUser(userBean);
                videoListBean.setId(dataBean.getId());
                videoListBean.setShareUrl(dataBean.getMedia_url());
                videoListBean.setTitle(dataBean.getTitle());
                videoListBean.setLocation(dataBean.getLocation());
                videoListBean.setCommentCount(dataBean.getComment_count());
                videoListBean.setPraiseCount(dataBean.getPraise_count());
                videoListBean.setForwardCount(dataBean.getForward_count());
                videoList.add(videoListBean);
            }
            videoPlayView.refreshVideoList(videoList, position);
        }

        if (hotdataList != null) {
            LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
            videoListBean.setVideoId(hotdataList.getMedia_id());
            videoListBean.setVideoUrl(hotdataList.getMedia_url());
            videoListBean.setFirstFrameUrl(hotdataList.getAvatar());
            videoListBean.setDescription(hotdataList.getDescription());
            BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
            VideoInfo.User user = hotdataList.getUser();
            if (user != null) {
                userBean.setAvatarUrl(user.getAvatar());
                userBean.setUserId(user.getId() + "");
                userBean.setUserName(user.getName());
            }
            videoListBean.setUser(userBean);
            videoListBean.setType(hotdataList.getType());
            videoListBean.setId(hotdataList.getId());
            videoListBean.setShareUrl(hotdataList.getMedia_url());//创视屏链接
            videoListBean.setTitle(hotdataList.getTitle());
            videoListBean.setLocation(hotdataList.getLocation());
            videoListBean.setCommentCount(hotdataList.getComment_count());
            videoListBean.setPraiseCount(hotdataList.getPraise_count());
            videoListBean.setForwardCount(hotdataList.getForward_count());
            videoListBean.setFollow_status(hotdataList.getFollow_status());
            videoList.add(videoListBean);
            videoPlayView.refreshVideoList(videoList, position);
        }

        if (hotdataListitem != null) {
            //热门item点击
            for (HotData1.VideosBean.DataBean dataBean : hotdataListitem.getDataList()) {
                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
                videoListBean.setVideoId(dataBean.getMedia_id());
                videoListBean.setVideoUrl(dataBean.getMedia_url());
                videoListBean.setFirstFrameUrl(dataBean.getAvatar());
                videoListBean.setDescription(dataBean.getDescription());
                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
                HotData1.VideosBean.DataBean.UserBean user = dataBean.getUser();
                if (user != null) {
                    userBean.setAvatarUrl(user.getAvatar());
                    userBean.setUserId(user.getId() + "");
                    userBean.setUserName(user.getName());
                    videoListBean.setUser(userBean);
                }
                videoListBean.setType(dataBean.getType());
                videoListBean.setId(dataBean.getId());
                videoListBean.setShareUrl(dataBean.getMedia_url());
                videoListBean.setTitle(dataBean.getTitle());
                videoListBean.setLocation(dataBean.getLocation());
                videoListBean.setCommentCount(dataBean.getComment_count());
                videoListBean.setPraiseCount(dataBean.getPraise_count());
                videoListBean.setForwardCount(dataBean.getForward_count());
                videoList.add(videoListBean);
            }
            videoPlayView.refreshVideoList(videoList, position);
        }


    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_play;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (videoPlayView != null) {
            videoPlayView.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (videoPlayView != null) {
            videoPlayView.onPause();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        netWatchdog.startWatch();
    }

    @Override
    public void onStop() {
        super.onStop();
        videoPlayView.onStop();
        netWatchdog.stopWatch();
    }

    @Override
    public void onDestroy() {
        videoPlayView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        videoPlayView.onDestroy();
    }

    private void initVideoPlayView() {

        videoPlayView = findViewById(R.id.video_play_detail_view);
        videoPlayView.setOnRefreshDataListener(new MyRefreshDataListener(VideoPlayActivity.this));
        videoPlayView.setOnStsInfoExpiredListener(new OnStsInfoExpiredListener() {
            @Override
            public void onTimeExpired() {
                //刷新获取STS
                StsInfoManager.getInstance().refreshStsToken(new MyStsResultListener(VideoPlayActivity.this));
            }

            @Override
            public StsTokenInfo refreshSts() {
                return StsInfoManager.getInstance().refreshStsToken();
            }
        });

        videoPlayView.setOnVideoDeleteListener(new AlivcVideoPlayView.OnVideoDeleteListener() {
            @Override
            public void onDeleteClick(LittleMineVideoInfo.VideoListBean video) {
            }
        });
//        videoPlayView.setOnPlayStatusListener(new AlivcVideoListView.OnPlayStatusListener() {
//            @Override
//            public void start() {
//            }
//
//            @Override
//            public void stop(IVideoSourceModel videoListBean, int position) {
//
//            }
//
//
//            @Override
//            public void onCompletion() {
//
//            }
//        });

        videoPlayView.setOnItemClickListener(new AlivcVideoPlayView.OnItemClickListener() {
            @Override
            public void onJumpComment(String videoId, String headerUrl, int commentCount, int position) {
                showBottomComment(videoId, headerUrl, commentCount, position);
            }

            @Override
            public void onJumpShare() {

            }

            @Override
            public void onJumpAdDetail(String link_type, String url) {

            }

            @Override
            public void onAdPlayStart() {

            }

            @Override
            public void onAdPlayPaused() {

            }

            @Override
            public void onAdPlayComplete() {

            }

        });
    }

    private HomeCommentFragment mHomeCommentFragment;


    public void showReviewFragment() {
        if (mHomeCommentFragment == null) return;
        mHomeCommentFragment.showBehavior();
    }

    /**
     * 隐藏评论页
     */
    public void hideReviewFragment() {
        if (mHomeCommentFragment == null) return;
        hideFragment(mHomeCommentFragment);
    }

    public void showBottomComment(String videoId, String headUrl, int commentCount, int position) {
        showFragment(R.id.fl_comment, mHomeCommentFragment = mHomeCommentFragment.newInstance(videoId, headUrl, commentCount, position), false);
        mHomeCommentFragment.setOnCommentListener(new HomeCommentFragment.OnCommentListener() {
            @Override
            public void onDismiss() {
                hideReviewFragment();
            }

            @Override
            public void onSlide(float ratio) {
            }
        });
        videoPlayView.postDelayed(() -> {
            showReviewFragment();
        }, 200);
    }

    /**
     * 接受更新评论事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateCommentNumberEvent(UpdateCommentNumberEvent event) {
        if (event != null && videoPlayView != null) {
            videoPlayView.updateCommentNumber(event.videoId, event.number, event.position);
            RecyclerView recyclerView = videoPlayView.getVideoListView().getRecycler();
            if (videoPlayView.getVideoListView() != null && recyclerView != null) {
                for (int i = 0; i < recyclerView.getChildCount(); i++) {
                    View child = recyclerView.getChildAt(i);
                    if (child.getTag() != null && child.getTag().toString().equals(event.position + "")) {
                        View tvNum = child.findViewById(R.id.tv_comment_number);
                        if (tvNum != null && tvNum instanceof TextView) {
                            ((TextView) tvNum).setText(NumberUtils.INSTANCE.convertOneDecimalW(event.number));
                        }
                        break;
                    }
                }
            }
        }
    }

    @Override
    public boolean isRegisterEventBus() {
        return true;
    }

    /**
     * 网络监听
     */
    public void initNetWatchDog() {
        netWatchdog = new NetWatchdog(this);
        netWatchdog.setNetConnectedListener(new MyNetConnectedListener(this));
    }

    private static class MyStsResultListener implements OnStsResultListener {
        WeakReference<VideoPlayActivity> weakReference;

        MyStsResultListener(VideoPlayActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onSuccess(StsTokenInfo tokenInfo) {
            VideoPlayActivity videoListActivity = weakReference.get();
            // videoListActivity.videoPlayView刷新sts信息
            videoListActivity.videoPlayView.refreshStsInfo(tokenInfo);
        }

        @Override
        public void onFail() {

        }
    }

    public static class MyRefreshDataListener implements AlivcVideoListView.OnRefreshDataListener {
        WeakReference<VideoPlayActivity> weakReference;

        MyRefreshDataListener(VideoPlayActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onRefresh() {
            if (weakReference == null) {
                return;
            }
            VideoPlayActivity activity = weakReference.get();
            if (activity != null) {
                activity.handler.postDelayed(() -> {
                    activity.videoPlayView.closeRefresh();
                }, 2000);

            }

        }


        @Override
        public void onLoadMore() {
            if (weakReference == null) {
                return;
            }
            VideoPlayActivity activity = weakReference.get();
            if (activity != null) {
                activity.videoPlayView.onStop();
            }
        }
    }

    private Handler handler = new Handler();

    public static class MyNetConnectedListener implements NetWatchdog.NetConnectedListener {
        private WeakReference<VideoPlayActivity> weakReference;

        MyNetConnectedListener(VideoPlayActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onReNetConnected(boolean isReconnect) {
            if (isReconnect) {
                //刷新获取STS
                StsInfoManager.getInstance().refreshStsToken(new VideoPlayActivity.MyStsResultListener(weakReference.get()));
                //网络重连
            }
        }

        @Override
        public void onNetUnConnected() {
            //网络断开
        }
    }
}
